package start

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/hexug/vblog/tree/master/api/apps"
	"gitee.com/hexug/vblog/tree/master/api/conf"
	"gitee.com/hexug/vblog/tree/master/api/logger"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var (
	configType string
	configPath string
	debug      bool
	Cmd        = &cobra.Command{
		Use:     "start",
		Short:   "启动服务",
		Long:    "启动服务",
		Example: "vblog-api start -t file -f etc/config.toml",
		Run: func(cmd *cobra.Command, args []string) {
			switch configType {
			case "file":
				cmd.Println("从file加载配置文件:", configPath)
				conf.LoadConfigFromToml(configPath)
			case "env":
				cmd.Println("从环境变量加载配置")
				conf.LoadConfigFromEnv()
			case "etcd":
				cmd.Println("尚未实现")
				return
			default:
				cmd.PrintErrln("选择的加载配置类型有误,目前只允许['file','env','etcd']")
				return
			}
			logger.L().Infoln("配置加载完成。")
			apps.InitApps()
			logger.L().Infoln("app初始化完成", debug)
			if !debug {
				gin.SetMode(gin.ReleaseMode)
			}
			engine := gin.Default()

			// cnf := cors.DefaultConfig()
			cnf := cors.New(cors.Config{
				AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
				AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
				AllowCredentials: true,
				MaxAge:           12 * time.Hour,
				// AllowAllOrigins:  true,
				AllowOrigins: []string{"http://localhost:5173"},
			})
			engine.Use(cnf)
			// engine.Use(Cors())
			router := engine.Group("/vblog/api/v1")
			apps.InitApis(router)
			svc := conf.C().Server
			err := engine.Run(fmt.Sprintf("%s:%d", svc.Host, svc.Port))
			// err := engine.Run(fmt.Sprintf("%s:%d", svc.Host, svc.Port))
			if err != nil {
				cmd.Println(err.Error())
			}
		},
	}
)

func Cors() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//以下是引用跨域 cookie
		ctx.Writer.Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))
		ctx.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Authorization,Set-Cookie")
		ctx.Writer.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
		ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		//如果请求方法为 options 则写入200
		if ctx.Request.Method == http.MethodOptions {
			ctx.AbortWithStatus(http.StatusOK)
		} else {
			ctx.Next()
		}
	}
}
func init() {
	Cmd.Flags().StringVarP(&configType, "config-type", "t", "file", "指定加载配置的类型")
	Cmd.Flags().StringVarP(&configPath, "config-path", "f", "etc/config.toml", "指定配置文件")
	Cmd.Flags().BoolVarP(&debug, "debug", "d", false, "开启debug模式")
}
